home *** CD-ROM | disk | FTP | other *** search
/ Pascal Super Library / Pascal Super Library (CW International)(1997).bin / LIBRARY / PAS_0793 / SHRTBASE.PAS < prev    next >
Pascal/Delphi Source File  |  1993-08-01  |  2KB  |  49 lines

  1. {─ Fido Pascal Conference ────────────────────────────────────────────── PASCAL ─
  2. Msg  : 290 of 314
  3. From : Ron Poulton                         1:153/9107.0         06 Jul 93  21:44
  4. To   : Mark Lewis
  5. Subj : Easy Base Conversion
  6. ────────────────────────────────────────────────────────────────────────────────
  7. Not to break your routine, but here's something people may find of use.
  8. It converts a decimal numeric to a string in any other base:}
  9.  
  10. Function Dec2Base(Decm : LongInt;Base,Len : Byte) : String;
  11. { D is the decimal number, B is the Base to convert it to, and Lis
  12.   the length of the return string (if the value is shorter, it will be
  13.   leftmostly padded with "0"'s }
  14. Var
  15.   SStr : String;
  16.   I : Byte;
  17.   H : LongInt;
  18. Begin
  19.   SStr[0]:=Chr(Len);
  20.   For I:=1 to Len do Begin
  21.     H:=Decm;
  22.     Decm:=H Div Base;
  23.     Dec (H,Decm*Base);
  24.     SStr[Len-I+1]:=Chr(H+48+7*Ord(H>9)){+SStr};
  25.   End;
  26.   Dec2Base:=SStr;
  27. End;
  28.  
  29. {DECM is the longinteger value of the number you want to convert, BASE is
  30. the destination base to convert to, and LEN is the maximum length of the
  31. resulting string.  Its counterpart converts a string numeric in a certain
  32. base to its decimal numeric value:}
  33.  
  34. Function Base2Dec(Num : String;Base : Byte) : LongInt;
  35. Var
  36.   Ret : LongInt;
  37.   I : Byte;
  38.   H : LongInt;
  39.   Len : Byte Absolute Num;
  40. Begin
  41.   Ret:=0;
  42.   For I:=1 to Len do Begin
  43.     H:=Ord(Num[I])-48;
  44.     Ret:=Ret*Base+H-7*Ord(H>9);
  45.   End;
  46.   Base2Dec:=Ret;
  47. End;
  48.  
  49. NUM is the string to convert, BASE is the base it's in.  Enjoy! :>